package com.sto.stoapp.manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.sto.stoapp.StoApplication;
import com.sto.stoapp.activity.R;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.widget.BaseDialog;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 强制升级apk包
 *
 * @author Administrator
 */
@SuppressLint("HandlerLeak")
public class DownShuRuFa {

    @SuppressWarnings("unused")
    private static final int ACTION_DEFAULT = 0x0; // 恢复系统默认
    private static final int ACTION_DIS_CANCEL_FINISH = 0X5A; // 都屏蔽
    @SuppressWarnings("unused")
    private static final int ACTION_DIS_CANCEL = 0XA; // 屏蔽取消button
    @SuppressWarnings("unused")
    private static final int ACTION_DIS_FINISH = 0x50; // 屏蔽完成button


    private final int TIME_OUT = 20 * 1000;

    private final int TIME_READ_OUT = 120 * 1000;

    private Context context;

    private String address;

    protected static final int PROGRESS_COUNT = 0;

    private ProgressBar progressBar;

    private TextView downCount, downTv;

    // private AlertDialog dialog;
    private BaseDialog dialog;

    private ExceptionClickListener listener;

    private String fileName = "Baiduinput.apk";

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == PROGRESS_COUNT) {
                updateProgress(msg.arg1);
            }
        }

    };

    private void updateProgress(int progress) {
        progressBar.setProgress(progress);
        downCount.setText(progress + "%");
        if (progress == 100) {
            downTv.setText("下载完成");
        }
    }

    public DownShuRuFa(Context context, String address) {
        this.context = context;
        this.address = address;
        View view = LayoutInflater.from(context).inflate(R.layout.down_apk,
                null);
        progressBar = (ProgressBar) view.findViewById(R.id.progress_horizontal);
        downCount = (TextView) view.findViewById(R.id.down_count);
        downTv = (TextView) view.findViewById(R.id.down_tv);
        dialog = new BaseDialog(context);
        dialog.setEnabledKeyEvent(false);
        dialog.showLog(view);

    }

    /**
     * 取消下载框
     */
    public void dismiss() {
        dialog.dismiss();
    }

    public void startDown() {
        downNewFile(address);
    }

    /**
     * 检测SD卡是否存在
     *
     * @return
     */
    private boolean ExistSDCard() {
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }

    // 下载APK包
    private void downNewFile(final String uri) {
        // final String apkName = uri.substring(uri.lastIndexOf("/") + 1,
        // uri.length());
        if (!ExistSDCard()) {
            Helper.showToast(context, context.getString(R.string.sd_unexists));
            dialog.dismiss();
            return;
        }
        new Thread() {
            public void run() {
                // 锁定cpu不让进入待机
                AlarmAlertWakeLockManager
                        .acquireCpuWakeLock(context, "upgrade");
                requstUpgrade();
                AlarmAlertWakeLockManager.releaseCpuLock("upgrade");

            }
        }.start();
    }

    private void requstUpgrade() {

        String result = HttpDownReqest(address);

    }

    private String HttpDownReqest(String uri) {
        String strResult = "";
        Log.d("download uri", uri);
        // String uriAPI = uri;
        // HttpClient client = new DefaultHttpClient();
        HttpClient client = setTimeOutClient();
        HttpGet get = new HttpGet(uri);
        try {
            // 取得HTTP response
            HttpResponse httpResponse = client.execute(get);

            // 若状态码为200 ok
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 取出回应字串
                try {
                    HttpEntity entity = httpResponse.getEntity();
                    long length = entity.getContentLength();

                    // strResult=EntityUtils.toString(entity);
                    // System.out.println("strResult:" + length+ "");

                    InputStream is = entity.getContent();
                    FileOutputStream fileOutputStream = null;
                    if (is != null) {
                        File file = new File(
                                Environment.getExternalStorageDirectory(),
                                fileName);
                        fileOutputStream = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int times = 0;
                        int count = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fileOutputStream.write(buf, 0, ch);
                            count += ch;
                            if (times == 30 || (count == length)) {
                                Message msg = handler.obtainMessage();
                                msg.what = PROGRESS_COUNT;
                                msg.arg1 = (int) (count * 100 / length);
                                msg.sendToTarget();
                                times = 0;
                                continue;
                            }
                            times++;
                        }
                        openFile(file);
                    }
                    fileOutputStream.flush();
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                    listener.onExceptionClickListener(context
                            .getString(R.string.upgrade_failed));
                } catch (IOException e) {
                    listener.onExceptionClickListener(context
                            .getString(R.string.upgrade_failed));
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            listener.onExceptionClickListener(context
                    .getString(R.string.upgrade_failed));
        }

        return strResult;
    }

    /**
     * 设置超时时间和创建httpClient
     *
     * @return
     */
    private HttpClient setTimeOutClient() {
        HttpParams params = new BasicHttpParams(); // 实例化Post参数对象
        HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);// 设置请求超时
        HttpConnectionParams.setSoTimeout(params, TIME_READ_OUT); // 设置响应超时
        HttpClient client = new DefaultHttpClient(params); // 实例化一个连接对象
        return client;
    }

    private void openFile(File file) {
        dialog.dismiss();
        StoApplication.getStoJni().StoJNI_InstallApkWithSilence(
                file.getPath(), true);
    }

    public void setListener(ExceptionClickListener listener) {
        this.listener = listener;
    }

    /**
     * 下载异常监听
     *
     * @author mgf
     */
    public interface ExceptionClickListener {
        void onExceptionClickListener(String exception);
    }
}
